package cn.com.yx.ms.controller;

import cn.com.yx.ms.application.web.ApiPager;
import cn.com.yx.ms.application.web.ApiQuery;
import cn.com.yx.ms.application.web.ApiQueryBase;
import cn.com.yx.ms.domain.dbmodel.ScFile;
import cn.com.yx.ms.domain.program.CatalogModel;
import cn.com.yx.ms.domain.program.UploadFileModel;
import cn.com.yx.ms.service.IProgramService;
import cn.yx.framework.configuration.AppConstant;
import cn.yx.framework.configuration.BaseConstant;
import cn.yx.framework.uploader.Plupload;
import cn.yx.framework.uploader.PluploadService;
import cn.yx.framework.util.DateUtil;
import cn.yx.framework.view.ApiResult;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.MessageSource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.Date;
import java.util.List;

import static org.springframework.web.bind.annotation.RequestMethod.GET;

/**
 * 应用中心
 */
@RestController
@RequestMapping(value = "/")
@Api(value = "素材管理", description = "获取或操作素材目录、素材等资源")
public class MaterialController {
    private static final Logger logger = LoggerFactory.getLogger(MaterialController.class);
    @Resource
    private MessageSource messageSource;
    @Resource
    private IProgramService iProgramService;
    @Resource
    private RedisTemplate redisTemplate;

    // region << 素材目录 >>
    @PostMapping("material/catalog")
    @ApiOperation(value = "创建素材目录信息", notes = "创建素材目录信息")
    @ApiImplicitParam(paramType = "body", name = "scCatalogModel", dataType = "Map", required = true, value = "素材目录实体详细信息")
    public ApiResult create(@RequestBody @Validated CatalogModel scCatalogModel, BindingResult bindingResult) {
        return iProgramService.saveScCatalog(scCatalogModel);
    }

    @DeleteMapping("material/catalogs/{id}")
    @ApiOperation(value = "删除素材目录信息", notes = "删除素材目录信息")
    @ApiImplicitParam(paramType = "path", name = "id", dataType = "String", required = true, value = "素材目录id")
    public ApiResult delete(@PathVariable("id") String id) {
        return iProgramService.deleteScCatalog(id);
    }

    @PutMapping("material/catalog")
    @ApiOperation(value = "更新素材目录信息", notes = "更新素材目录信息")
    @ApiImplicitParam(paramType = "body", name = "orgModel", dataType = "Map", required = true, value = "素材目录信息")
    public ApiResult updateModel(@RequestBody @Validated CatalogModel scCatalogModel, BindingResult bindingResult) {
        return iProgramService.saveScCatalog(scCatalogModel);
    }

    @PatchMapping("material/catalog")
    @ApiOperation(value = "素材目录信息部分更新", notes = "素材目录信息部分更新")
    @ApiImplicitParam(paramType = "body", name = "orgModel", dataType = "Map", required = true, value = "素材目录信息")
    public ApiResult updateProperty(@RequestBody @Validated CatalogModel scCatalogModel, BindingResult bindingResult) {
        //return new ApiResult<>(AppConstant.MSG_SUCCESS, true, "更新成功", iTestService.update(testModel));
        return null;
    }


    @ResponseBody
    @RequestMapping(value = "material/catalogs", method = RequestMethod.GET)
    @ApiOperation("获取所有素材目录信息")
    public ApiResult find(@ApiQuery ApiQueryBase query, HttpServletRequest request) {

        query.getConditions().put("catalogname", request.getParameter("catalogname"));
        return new ApiResult<>(AppConstant.MSG_SUCCESS,
                true,
                "",
                iProgramService.findScCatalogs(query));

    }


    @ResponseBody
    @RequestMapping(value = "material/catalogs/{id}", method = GET)
    @ApiImplicitParam(paramType = "String", name = "id", dataType = "String", required = true, value = "素材目录ID")
    @ApiOperation("获取单个素材目录信息")
    public ApiResult findById(@PathVariable("id") String id) {
        return new ApiResult<>(AppConstant.MSG_SUCCESS, iProgramService.findScCatalog(id));
    }

    // endregion

    // region << 素材管理 >>

    @ResponseBody
    @RequestMapping(value = "material/files/page", method = RequestMethod.GET)
    @ApiOperation("获取带分页的素材信息")
    public ApiResult findFilesPage(@ApiQuery ApiQueryBase query, HttpServletRequest request) {

        // 查询条件接受
        query.getConditions().put("ps", request.getParameter("ps"));
        query.getConditions().put("pi", request.getParameter("pi"));
        query.getConditions().put("filename", request.getParameter("filename"));
        query.getConditions().put("catalogid", request.getParameter("catalogid"));


        // 翻页对象构建
        PageHelper.startPage(query.getPi(), query.getPs(), true);
        Page<ScFile> page = (Page<ScFile>) iProgramService.findScFiles(query);
        ApiPager<ScFile> apiPager = new ApiPager<ScFile>(query.getPs(),
                query.getPi(),
                page.getTotal(),
                page.getResult());

        return new ApiResult<>(AppConstant.MSG_SUCCESS, true, request.getSession().getId(), apiPager);

    }

    @PostMapping("material/file")
    @ApiOperation(value = "上传文件信息", notes = "上传文件信息")
    public ApiResult postFile(Plupload plupload, HttpServletRequest request) {
        System.out.println(plupload);
        plupload.setRequest(request);//手动传入Plupload对象HttpServletRequest属性
        File dir = new File(BaseConstant.getUploadConfig().getFilepath() + "/" + DateUtil.date2String(new Date(), "yyyyMM"));
        if (!dir.exists()) {
            dir.mkdirs();//可创建多级目录，而mkdir()只能创建一级目录
        }
        //开始上传文件
        PluploadService.upload(plupload, dir);
        return new ApiResult().success();
    }

    @GetMapping("material/files/{md5}")
    @ApiImplicitParam(paramType = "String", name = "id", dataType = "String", required = true, value = "素材目录ID")
    @ApiOperation(value = "上传文件信息", notes = "上传文件信息")
    public ApiResult sameMd5File(@PathVariable("md5") String md5) {
        System.out.println(md5);
        int count = iProgramService.selectCountByMd5(md5);
        return new ApiResult(AppConstant.MSG_SUCCESS, true, "", count);
    }

    @PostMapping("material/files/{folderid}")
    @ApiOperation(value = "上传文件信息", notes = "上传文件信息")
    public ApiResult saveDbFiles(@PathVariable("folderid") String folderid,
                                 @RequestBody List<UploadFileModel> uploadFileModels,
                                 HttpServletRequest request) {
        return new ApiResult(AppConstant.MSG_SUCCESS,
                true,
                "",
                iProgramService.saveFiles(folderid, uploadFileModels, request));
    }

    @DeleteMapping("material/files/{id}")
    @ApiOperation(value = "删除素材信息", notes = "删除素材信息")
    @ApiImplicitParam(paramType = "path", name = "id", dataType = "String", required = true, value = "素材目录id")
    public ApiResult deleteFile(@PathVariable("id") String id) {
        return new ApiResult<>(AppConstant.MSG_SUCCESS, iProgramService.deleteScFile(id));
    }


    @ResponseBody
    @RequestMapping(value = "material/catalogfiletree", method = RequestMethod.GET)
    @ApiOperation("获取素材文件树信息")
    public ApiResult findCatalogFileTree() {
        return new ApiResult(AppConstant.MSG_SUCCESS, true, "", iProgramService.findCatalogFileTree());
    }

    @ResponseBody
    @RequestMapping(value = "material/ggfiletree", method = RequestMethod.GET)
    @ApiOperation("获取素材文件树信息")
    public ApiResult findGgFileTree() {
        return new ApiResult(AppConstant.MSG_SUCCESS, true, "", iProgramService.findGgFileTree());
    }


//    @PostMapping("live")
//    @ApiOperation(value = "创建直播流", notes = "创建直播流")
//    @ApiImplicitParam(paramType = "body", name = "scFileModel", dataType = "Map", required = true, value = "直播流详细信息")
//    public ApiResult createLive(@RequestBody @Validated ScFileModel scFileModel, BindingResult bindingResult) throws Exception {
//        return iProgramService.saveScFile(scFileModel);
//
//    }
//`
//    @DeleteMapping("lives/{id}")
//    @ApiOperation(value = "删除直播流信息", notes = "删除直播流信息")
//    @ApiImplicitParam(paramType = "path", name = "id", dataType = "String", required = true, value = "角色id")
//    public ApiResult deleteLive(@PathVariable("id") String id) {
//        return new ApiResult<>(AppConstant.MSG_SUCCESS, iProgramService.deleteScFile(id));
//    }
//
//    @PutMapping("live")
//    @ApiOperation(value = "更新直播流信息", notes = "更新直播流信息")
//    @ApiImplicitParam(paramType = "body", name = "scFileModel", dataType = "Map", required = true, value = "直播流实体详细信息")
//    public ApiResult updateLiveModel(@RequestBody @Validated ScFileModel scFileModel, BindingResult bindingResult) {
//        return iProgramService.saveScFile(scFileModel);
//    }
//
//    @ResponseBody
//    @RequestMapping(value = "lives/{id}", method = GET)
//    @ApiImplicitParam(paramType = "String", name = "id", dataType = "String", required = true, value = "角色ID")
//    @ApiOperation("获取单个直播流素材信息")
//    public ApiResult findLiveById(@PathVariable("id") String id) {
//        return new ApiResult<>(AppConstant.MSG_SUCCESS, iProgramService.findScFile(id));
//    }
    // endregion

}